package com.sparrow.common.mergeupdate.impl;

import com.sparrow.common.mergeupdate.MergeUpdateBox;
import com.sparrow.common.thread.IdExecutorGroup;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 合并更新之-延迟合并
 * 设置一个固定的延迟时间（如 100ms），在此时间内不断收集更新请求，不立即执行，而是延迟到时间到达后统一处理
 */
public class DelayMergeBox implements MergeUpdateBox {


    private ConcurrentHashMap<Object, DelayMergeScheduler> dataMap = new ConcurrentHashMap<>();

    public MergeUpdateScheduler getMergeUpdateScheduler(Object key) {
        return dataMap.computeIfAbsent(key, k -> new DelayMergeScheduler());
    }

    public static class DelayMergeScheduler implements MergeUpdateBox.MergeUpdateScheduler {
        private AtomicBoolean changeStatus = new AtomicBoolean(false);

        public void tryMergeSchedule(IdExecutorGroup executorGroup, long id, String taskName, Runnable r, long delay, TimeUnit unit) {
            if (!changeStatus.compareAndSet(false, true)) {
                return; // 已调度，不重复调度
            }

            executorGroup.schedule(id, taskName, () -> {
                if (changeStatus.compareAndSet(true, false)) {
                    r.run();
                }
            }, delay, unit);
        }
    }

}
